package cn.jekun.shop.common.service;

import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.McMember;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.McMemberService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.shop.app.bean.Member;

@Service(MemberService.BEAN_NAME)
public class MemberService extends ShopBaseService {
	public static final String BEAN_NAME = "cn.jekun.shop.common.MemberService";

	@Override
	public String getNamespace() {
		return "SHOP_MEMBER_USER";
	}

	@Resource(name = ErpOrdersService.BEAN_NAME)
	ErpOrdersService erpOrdersService;

	@Resource(name = RsUserService.BEAN_NAME)
	RsUserService rsUserService;
	@Resource(name = McMemberService.BEAN_NAME)
	McMemberService memberService;

	/**
	 * 会员详情
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getMemberDetails(
			@Security
			@RsUser.AnnoUserId
			String userId, 
			@Security
			String shopId) {

		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "用户代码不能为空");
		}
		if (StringUtils.isBlank(shopId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商家代码不能为空");
		}
		JSONObject jsonObject = new JSONObject();

		try {
			Map map = new HashMap();
			map.put("userId", userId);
			map.put("shopId", shopId);
			// 会员详情
			Member member = this.one(this.getStatementName("details"), map);

			jsonObject.put("data", member);

		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);

	}

	/**
	 * 会员交易记录
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getMemberTrans(
			@RsUser.AnnoUserId
			String userId, 
			@Security
			String shopId) {

		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "用户代码不能为空");
		}
		if (StringUtils.isBlank(shopId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商家代码不能为空");
		}
		JSONObject jsonObject = new JSONObject();

		try {
			Map map = new HashMap();
			map.put(ErpOrders.COL_USER_ID, userId);
			map.put(ErpOrders.COL_SHOP_ID, shopId);

			SqlUtis.prepareSql(map, SqlUtis.getSQL(map, ErpOrders.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis.getSQL(map, ErpOrders.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ));

			List<ErpOrders> Orders = this.erpOrdersService.list(map);

			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
			jsonObject.put("data", JSONArray.fromObject(Orders, jsonConfig));

		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);

	}

	/**
	 * 会员列表
	 * @param shopId 商户代码
	 * @param pageSize  页大小
	 * @param currentPage 当前页
	 * @param memberTypeId 加入方式
	 * @param endDate 时间
	 * @param userName 会员账号
	 * @param memoName 备注名
	 * @param mobile 手机号
	 * @return
	 */
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getMemberList(
			@Security
			String shopId,
			@Security
			String pageSize,
			@Security
			String currentPage,
			@Security
			String memberTypeId,
			Date endDate,
			@Security
			String userName,
			@Security
			String memoName,
			@Mobile(message="手机号非法")
			String mobile) {
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商家代码不能为空");
		}
		if(StringUtils.isNotBlank(pageSize)){
			page.setPageSize(Integer.parseInt(pageSize));
		}
		if(StringUtils.isNotBlank(currentPage)){
			page.setPageNumber(Integer.parseInt(currentPage));
		}
		if(StringUtils.isNotBlank(memberTypeId)){
			formMap.put(McMember.COL_MEMBER_TYPE_ID, memberTypeId);
		}
		if(StringUtils.isNotBlank(userName)){
			formMap.put(RsUser.COL_USER_NAME, userName);
		}
		if(StringUtils.isNotBlank(memoName)){
			formMap.put(McMember.COL_MEMO_NAME, memoName);
		}
		if(StringUtils.isNotBlank(mobile)){
			formMap.put(RsUser.COL_MOBILE, mobile);
		}
		if (endDate!=null) {
			formMap.put("date", DateFormatUtils.format(endDate,"yyyy-MM-dd"));
			}
		formMap.put(ErpShop.COL_SHOP_ID, shopId);
		Map tempMap = new HashMap();
		Page tempPage = new Page();
		tempMap.put(ErpShop.COL_SHOP_ID, shopId);
		SqlUtis.prepareSql(tempMap, "",
				SqlUtis.getSQL(tempMap, "a."+ McMember.COL_SHOP_ID, Types.VARCHAR,SqlUtis.EQ));
		this.list(this.getStatementName("list2"),tempMap, tempPage);
		SqlUtis.prepareSql(formMap, "",
				SqlUtis.getSQL(formMap, "a."+ McMember.COL_SHOP_ID, Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(formMap, "b."+ RsUser.COL_USER_NAME, Types.VARCHAR,SqlUtis.LIKE),
				SqlUtis.getSQL(formMap, "a."+ McMember.COL_MEMBER_TYPE_ID, Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(formMap, "a."+ McMember.COL_MEMO_NAME, Types.VARCHAR,SqlUtis.LIKE),
				SqlUtis.getSQL(formMap, "b."+ RsUser.COL_MOBILE, Types.VARCHAR,SqlUtis.EQ));
		resultList =this.list(this.getStatementName("list2"),formMap, page);
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); 
		JSONArray jsonArray = JSONArray.fromObject(resultList, jsonConfig);
		jsonObject.put("memberList", jsonArray);
		jsonObject.put("pageSize",page.getPageSize());
		jsonObject.put("currentPage", page.getPageNumber());
		List<Map> list = this.memberService.listBySql("select count(1)as count from mc_member a where (a.create_time >= to_date(to_char(sysdate,'yyyy-mm-dd'),'yyyy-mm-dd')) and a.shop_id='"+shopId+"'");
		String newMember = list.get(0).get("COUNT").toString();
		jsonObject.put("totalMember", tempPage.getTotalCount());//会员总数
		jsonObject.put("newMember", newMember);//今日日新增会员数
		jsonObject.put("totals", page.getPages());
		return executeRerutn(jsonObject);
	}

	/**
	 * 统计会员在商家中的累计消费
	 * @param memberId
	 * @param userId
	 */
	@SuppressWarnings("unchecked")
	public JSONObject getTotalPayMoney(
			@RsUser.AnnoUserId
			String userId, 
			@Security
			String shopId
			) {
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商家代码不能为空");
		}
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"会员代码不能为空");
		}
		List templist = this.listBySql("select a.* from erp_orders a where a.order_status_id='3' and a.user_id='"+userId+"' and a.shop_id='"+shopId+"'");
		String mount = "";
		if(templist == null || templist.size()==0){
			mount = "0.0";
		}else{
			List<Map> list = this.listBySql("select sum(a.total_amount) as mount from erp_orders a where a.order_status_id='3' and a.user_id='"+userId+"' and a.shop_id='"+shopId+"'");
			mount = list.get(0).get("MOUNT").toString();
		}
		jsonObject.put("totalMount", mount);
		return executeRerutn(jsonObject);
	}
	/**
	 * 商家添加会员
	 * 
	 * @param shopId
	 * @param moblie
	 * @param realName
	 * @param memoName
	 * @param password
	 * @return
	 */
	@Transactional
	public JSONObject addMember(
			@Security
			String shopId, 
			@Mobile(message="手机号非法")
			String mobile, 
			@Security
			String realName, 
			@Security
			String memoName,
			@Security
			String password, 
			@Security
			String phoneNum,
			@Security
			String sex,
			@Security
			String job, 
			@Security
			String birthday, 
			@Security
			String address) {
		JSONObject jsonObject = new JSONObject();
		RsUser rsUser = null;
		McMember mcMember = null;
		String memberId = "";
		Map formMap = new HashMap(); // 查询条件集合

		if (StringUtils.isBlank(shopId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商戶代码不为空");
		}
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "手机号码不为空");
		}
		/*if (StringUtils.isBlank(realName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "真实姓名不为空");
		}*/
		/*if (StringUtils.isBlank(memoName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "备注姓名不为空");
		}*/

		formMap.put(RsUser.COL_MOBILE, mobile); // 添加查询的条件
		SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a." + RsUser.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
		// System.out.println(formMap);
		String userId = "";

		try {
			rsUser = rsUserService.one(formMap); // 查询用户是否存在
			if (rsUser != null) {
				userId = rsUser.getUserId(); // 用户代码
			} else {
				rsUser = new RsUser(); // 创建用户实体
				rsUser.setShopId(shopId);
				rsUser.setMobile(mobile); // 用户手机号码
				rsUser.setRealName(realName); // 用户真实姓名
				rsUser.setUserName(mobile); // 用户名（手机号码）
				rsUser.setPassword(EncryptUtil.md5(password)); // 用户密码，采用md5加密
				rsUser.setAddress(address); // 地址
				rsUser.setBirthday(convertToDate(birthday)); // 生日
				rsUser.setInviteUserId(shopId); // 邀请人
				rsUser.setSex(sex); // 性別
				rsUser.setPhoneNumber(phoneNum);// 固定電話
				rsUser.setAddress(address); // 地址
				Map rsUserMap = new HashMap(); // 条件容器
				rsUserMap.put("rsUser", rsUser);
				userId = rsUserService.insert(rsUserMap).toString(); // 添加用户
			}
			Map memberMap = new HashMap();
			memberMap.put(McMember.COL_USER_ID, userId);
			memberMap.put(McMember.COL_SHOP_ID, shopId);
			SqlUtis.prepareSql(memberMap, SqlUtis.getSQL(memberMap, "a." + McMember.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ),
					SqlUtis.getSQL(memberMap, "a." + McMember.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ));
			mcMember = memberService.one(memberMap);
			if (mcMember == null) {
				mcMember = new McMember();
				memberMap = new HashMap();
				mcMember.setUserId(userId); // 用户代码
				mcMember.setMemoName(memoName); // 备注名
				mcMember.setShopId(shopId); // 商户代码
				mcMember.setMemberTypeId("3"); // 加入方式,手机注册
				mcMember.setCredits(0.0); // 积分
				memberMap.put("mcMember", mcMember); // 条件容器
				memberId = memberService.insert(memberMap).toString();
			}else{
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "该商家已有此会员");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return this.executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}

	/**
	 * 修改商户的备注姓名
	 * 
	 * @param memberId
	 * @param memoName
	 * @return
	 */
	@Transactional
	public JSONObject editMember(
			@Security
			String memberId, 
			@Security
			String memoName) {
		JSONObject jsonObject = new JSONObject(); 
		McMember mcMember = new McMember(); //创建会员实体
		if (StringUtils.isBlank(memberId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "会员编码不能为空");
		}
		if (StringUtils.isBlank(memoName)) {
			memoName = "";
		}
		try {
			Map formMap = new HashMap();
			mcMember.setMemoName(memoName); //备注姓名
			formMap = new HashMap(); 
			formMap.put(McMember.COL_MEMBER_ID, memberId); //会员代码
			formMap.put("mcMember", mcMember); //会员实体
			SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a." + McMember.COL_MEMBER_ID, Types.VARCHAR, SqlUtis.EQ));
			memberService.update(formMap);
		} catch (Exception e) {
			e.printStackTrace();
			return this.executeRerutnFail(jsonObject);
		}
		return this.executeRerutn(jsonObject);
	}
	/**
	 * 将字符串200-15-18格式转换成java.util.Date
	 * @param str
	 * @return
	 */
	public  Date convertToDate(String str) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
		date = (Date) df.parse(str);
		} catch (Exception e) {
		e.printStackTrace();
		}
		return date;
		}
	/**
	 * 是不是该商家的会员
	 * @param tempUserId 被测试会员的用户代码
	 * @param shopId 商家代码
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject isMember(
			@Security
			String tempUserId, 
			@Security
			String shopId) {
		JSONObject jsonObject = new JSONObject(); 
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商家代码不能为空");
		}
		if(StringUtils.isBlank(tempUserId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"会员的用户代码不能为空");
		}
		Map tempMap = new HashMap();
		tempMap.put(McMember.COL_USER_ID, tempUserId);
		tempMap.put(McMember.COL_SHOP_ID, shopId);
		SqlUtis.prepareSql(tempMap, 
				SqlUtis.getSQL(tempMap, "a." + McMember.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(tempMap, "a." + McMember.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ));
		boolean flag = this.memberService.exists(tempMap);
		if(flag){
			return executeRerutn(jsonObject);
		}else{
			jsonObject.put(ErrorMsg.KEY_MESSAGE, "此用户不是该商家会员");
			return executeRerutnFail(jsonObject);
		}
	}
}
